package com.guinea;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import javax.sql.DataSource;

import org.dbunit.DatabaseUnitException;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.ext.h2.H2Connection;
import org.dbunit.ext.oracle.OracleConnection;
import org.dbunit.operation.DatabaseOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import org.springframework.beans.factory.InitializingBean;

public class DataPopulator {
	private Logger logger = LoggerFactory.getLogger(DataPopulator.class);
	private ResourceLoader resourceLoader = new DefaultResourceLoader();
	private static final String H2 = "h2";
	private DataSource dataSource;
	private DataSource svwDataSource;
	private String[] xmlFilePaths;
	private String[] tables;
	private String dbType;
	
	public DataSource getDataSource() {
		return dataSource;
	}
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	public String[] getXmlFilePaths() {
		return xmlFilePaths;
	}
	public void setXmlFilePaths(String[] xmlFilePaths) {
		this.xmlFilePaths = xmlFilePaths;
	}
	
	public String[] getTables() {
		return tables;
	}
	public void setTables(String[] tables) {
		this.tables = tables;
	}
	public String getDbType() {
		return dbType;
	}
	public void setDbType(String dbType) {
		this.dbType = dbType;
	}
	
	public DataSource getSvwDataSource() {
		return svwDataSource;
	}
	public void setSvwDataSource(DataSource svwDataSource) {
		this.svwDataSource = svwDataSource;
	}
	public void afterPropertiesSet() throws Exception {
//		execute(dbType,DatabaseOperation.UPDATE,dataSource,xmlFilePaths);
		execute(dbType,DatabaseOperation.DELETE_ALL,dataSource,xmlFilePaths);
		execute(dbType,DatabaseOperation.INSERT,dataSource,xmlFilePaths);
	}
	public void executeCities() throws Exception {
		execute(dbType,DatabaseOperation.CLEAN_INSERT,dataSource,new String[]{"data/cities.xml"});
	}
	/**
	 * 按DBUnit Operation执行XML数据文件的数据.
	 * 
	 * @param xmlFilePaths 符合Spring Resource路径格式的文件列表.
	 */
	private void execute(String dbType, DatabaseOperation operation, DataSource dataSource, String[] xmlFilePaths)
			throws DatabaseUnitException, SQLException {
		IDatabaseConnection connection = null;
		if(DataPopulator.H2.equalsIgnoreCase(dbType))
			connection = new H2Connection(dataSource.getConnection(), "");
		if(connection != null)
		for (int i = 0; i < xmlFilePaths.length; i++) {
			String xmlPath = xmlFilePaths[i];
			try {
				InputStream input = resourceLoader.getResource(xmlPath).getInputStream();
				IDataSet dataSet = new FlatXmlDataSetBuilder().setColumnSensing(true).build(input);
				operation.execute(connection, dataSet);
			} catch (IOException e) {
				logger.warn(xmlPath + " file not found", e);
			}
		}
	}
	
	public void export() throws DatabaseUnitException, SQLException, FileNotFoundException, IOException{
		IDatabaseConnection connection = null;
		if(H2.equalsIgnoreCase(dbType))
			connection = new H2Connection(dataSource.getConnection(), "");
		if(connection != null) {
//	        // partial database export
//	        QueryDataSet partialDataSet = new QueryDataSet(connection);
//	        for (int i = 0; i < tables.length; i++) {
//	        	partialDataSet.addTable(tables[i]);
//			}
//	        FlatXmlDataSet.write(partialDataSet, new FileOutputStream("default-data.xml"));

	        // full database export
	        IDataSet fullDataSet = connection.createDataSet();
	        FlatXmlDataSet.write(fullDataSet, new FileOutputStream("src/main/resources/data/full.xml"));
		}
	}
	public void exportSvw() throws DatabaseUnitException, SQLException, FileNotFoundException, IOException{
		IDatabaseConnection connection = null;
		connection = new OracleConnection(svwDataSource.getConnection(), "");
		if(connection != null) {
	        // partial database export
	        QueryDataSet partialDataSet = new QueryDataSet(connection);
//	        for (int i = 0; i < tables.length; i++) {
//	        	partialDataSet.addTable(tables[i]);
//			}
	        partialDataSet.addTable("TDN_PROVINCE","select * from tdn_province");
	        partialDataSet.addTable("TDN_CITY","select * from tdn_city");
	        partialDataSet.addTable("TDN_DISTRICT","select * from tdn_district");
	        FlatXmlDataSet.write(partialDataSet, new FileOutputStream("src/main/resources/data/cities.xml"));

	        // full database export
//	        IDataSet fullDataSet = connection.createDataSet();
//	        FlatXmlDataSet.write(fullDataSet, new FileOutputStream("src/main/resources/data/full.xml"));
		}
	}
}
